package cn.unknowpupil.init.configure.swagger;

/**
 * @Description: 描述。</br>
 * <p>
 *
 * </p>
 * @Author: <a> w10g </a>
 * @Since: 2020/7/5 20:14
 */

import io.swagger.models.auth.In;
import org.springframework.boot.SpringBootVersion;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.builders.ResponseBuilder;
import springfox.documentation.oas.annotations.EnableOpenApi;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.Response;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.service.SecurityScheme;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;


/**
 * @Classname: SwaggerConfig
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2020/4/13 12:04
 * @Description:
 * @Version: 1.0
 */
@EnableOpenApi
@Configuration
public class SwaggerConfiguration {

    /**
     * @请求头设置
     */
    public final static String HEADER = "Authorization";
    public final static String ADMIN_HEADER = "X-Token";
    public final static String TOKEN_SPLIT = "Bearer ";
    public final static String KEY = "header";

//    weight=1 max_fails=0 fail_timeout=30s
    private final SwaggerProperties swaggerProperties;

    public SwaggerConfiguration(SwaggerProperties swaggerProperties) {
        this.swaggerProperties = swaggerProperties;
    }


    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.OAS_30).pathMapping("/")
                .groupName("前端接口")
                // 定义是否开启swagger，false为关闭，可以通过变量控制
                .enable(swaggerProperties.getEnable())
                // 将api的元信息设置为包含在json ResourceListing响应中。
                .apiInfo(apiInfo())
                // 接口调试地址
                .host(swaggerProperties.getTryHost())
                // 选择哪些接口作为swagger的doc发布
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.regex("/api/.*"))
                .build()
                .globalResponses(HttpMethod.GET, getGlobalResponsesMessage())
                .globalResponses(HttpMethod.POST, getGlobalResponsesMessage())
                // 支持的通讯协议集合
                .protocols(newHashSet("https", "http"))
                // 授权信息设置，必要的header token等认证信息
                .securitySchemes(securitySchemes(HEADER,HEADER))
                // 授权信息全局应用
                .securityContexts(securityContexts(HEADER));
    }

    @Bean
    public Docket createBackApi() {
        return new Docket(DocumentationType.OAS_30).pathMapping("/")
                .groupName("后端接口")
                // 定义是否开启swagger，false为关闭，可以通过变量控制
                .enable(swaggerProperties.getEnable())
                // 将api的元信息设置为包含在json ResourceListing响应中。
                .apiInfo(apiInfo())
                // 接口调试地址
                .host(swaggerProperties.getTryHost())
                // 选择哪些接口作为swagger的doc发布
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.regex("/admin/.*"))
                .build()
                .globalResponses(HttpMethod.GET, getGlobalResponsesMessage())
                .globalResponses(HttpMethod.POST, getGlobalResponsesMessage())
                // 支持的通讯协议集合
                .protocols(newHashSet("https", "http"))
                // 授权信息设置，必要的header token等认证信息
                .securitySchemes(securitySchemes(HEADER,HEADER))
                // 授权信息全局应用
                .securityContexts(securityContexts(HEADER));
    }
    @Bean
    public Docket createCommonApi() {
        return new Docket(DocumentationType.OAS_30).pathMapping("/")
                .groupName("公共接口")
                // 定义是否开启swagger，false为关闭，可以通过变量控制
                .enable(swaggerProperties.getEnable())
                // 将api的元信息设置为包含在json ResourceListing响应中。
                .apiInfo(apiInfo())
                // 接口调试地址
                .host(swaggerProperties.getTryHost())
                // 选择哪些接口作为swagger的doc发布
                .select()
                .apis(RequestHandlerSelectors.any())
                .paths(PathSelectors.regex("/common/.*"))
                .build()
                .globalResponses(HttpMethod.GET, getGlobalResponsesMessage())
                .globalResponses(HttpMethod.POST, getGlobalResponsesMessage())
                // 支持的通讯协议集合
                .protocols(newHashSet("https", "http"));
    }
    /**
     * API 页面上半部分展示信息
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder().title(swaggerProperties.getApplicationName() + " Api Doc")
                .description(swaggerProperties.getApplicationDescription())
                .contact(new Contact("unknowpupil", null, "unknowpupil@gmail.com"))
                .version("Application Version: " + swaggerProperties.getApplicationVersion() + ", Spring Boot Version: " + SpringBootVersion.getVersion())
                .build();
    }

    /**
     * 设置授权信息
     */
    private List<SecurityScheme> securitySchemes(String name,String keyName) {
        ApiKey apiKey = new ApiKey(name, keyName, In.HEADER.toValue());
        return Collections.singletonList(apiKey);
    }

    /**
     * 授权信息全局应用
     */
    private List<SecurityContext> securityContexts(String reference) {
        return Collections.singletonList(
                SecurityContext.builder()
                        .securityReferences(Collections.singletonList(new SecurityReference(reference, new AuthorizationScope[]{new AuthorizationScope("global", "")})))
                        .build()
        );
    }


    @SafeVarargs
    private final <T> Set<T> newHashSet(T... ts) {
        if (ts.length > 0) {
            return new LinkedHashSet<>(Arrays.asList(ts));
        }
        return null;
    }

    /**
     * Created at 2020/10/14 by w10g <br>
     * Initialize getGlobalResponsesMessage  生成通用响应信息...<br>
     * @since 0.0.1
     * @author w10g
     * @return
    */
    private List<Response> getGlobalResponsesMessage() {
        List<Response> responseList = new ArrayList<>();
        responseList.add(new ResponseBuilder().code("404").description("找不到资源").build());
        return responseList;
    }
}
